<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\controller;
use app\common\model\BonusLog;
use app\common\model\Member;
use think\Controller;
use think\Db;
use app\common\model\UserAccount;
use app\common\model\UserAccountLog;

class Application extends ApiBase
{

    //应用列表
    public function lists(){

//        $userid = decoded_user_token(input("user_token"),'member_id');

        $class = Db::name('application_class')->where(['status'=>1])->select();
        foreach ($class as $k=>$v){
            $class[$k]['application'] = Db::name('application')->where(['status'=>1,'class'=>$v['id']])->order('id desc')->select();
            foreach($class[$k]['application'] as $key=>$value){
                $class[$k]['application'][$key]['logo'] = get_picture_url($value['logo'],false);
            }
        }
        if(empty($class)){
            echo json_encode(ajaxreturn(0,lang('暂无数据'),[]));
        }else{
            echo json_encode(ajaxreturn(0,lang('查询成功'),$class));
        }
    }

    //应用详情
    public function detail(){
        $id = input('id');
        $info = Db::name('application')->where(['id'=>$id])->find();
        $info['describer']=html_change($info['describer']);
        $info['logo']=get_picture_url($info['logo'],false);
        if(empty($info)){
            echo json_encode(ajaxreturn(1,lang('参数错误')));
        }else{
            echo json_encode(ajaxreturn(0,lang('查询成功'),$info));
        }
    }

    //购买应用
    public function buy(){
        $id = input('id');
        $number = input('number');
        $application = Db::name('application')->where(['id'=>$id,'status'=>1])->find();
        if(empty($application)){
            echo json_encode(ajaxreturn(1,lang('应用不存在')));exit;
        }
        if(empty($application['number'])){
            echo json_encode(ajaxreturn(1,lang('库存不足')));exit;
        }
        $userid = decoded_user_token(input("user_token"),'member_id');
//        if(!empty($application['limit_buy'])){
//           $order_count=Db::name("application_order")->where(['user_id'=>$userid,'status'=>['in',[1,2]]])->count();
//           if($order_count>=$application['limit_buy']){
//               echo json_encode(ajaxreturn(1,lang('已达到购买上限')));exit;
//           }
//        }
//
//        if(!empty($application['limit_order'])){
//            $order_count=Db::name("application_order")->where(['app_id'=>$application['id'],'user_id'=>$userid,'create_time'=>['between',[getTodayStart(),TIME_NOW]]])->count();
//            if($order_count>=$application['limit_order']){
//                echo json_encode(ajaxreturn(1,lang('今日订单已达到购买上限')));exit;
//            }
//        }
        empty($this->param['type'])  && $this->param['type']=1;
        $member = Db::name('member')->where(['id'=>$userid])->find();
        if($this->param['type']==1 || $this->param['type']==2){
            $ticket = Db::name('application_ticket')->where(['id'=>$this->param['ticket_id'],'status'=>1])->find();
            if(empty($ticket)){
                echo json_encode(ajaxreturn(1,lang('应用券不存在')));exit;
            }

            //判断用户余额
            if($member['app_balance']<$ticket['price']){
                echo json_encode(ajaxreturn(1,lang('应用余额不足')));exit;
            }
        }else{
            if(empty($this->param['account'])){
                echo json_encode(ajaxreturn(1,lang('账号或者手机不能为空')));exit;
            }
            $ticket = Db::name('application_membercard')->where(['id'=>$this->param['ticket_id'],'status'=>1])->find();
            if(empty($ticket)){
                echo json_encode(ajaxreturn(1,lang('会员卡不存在')));exit;
            }
            //判断用户余额
            if($member['app_balance']<$ticket['real_price']){
                echo json_encode(ajaxreturn(1,lang('应用余额不足')));exit;
            }
        }

        Db::startTrans();
        try{
            $sn = "APP".$userid.time();
            $data = array(
                "sn"=>$sn,
                "user_id"=>$userid,
                'type'=>$this->param['type'],
                "ticket_id"=>$ticket['id'],
                "app_id"=>$application['id'],
                'status'=>0,
                'create_time'=>time(),
                'update_time'=>time(),
                'number'=> $number
            );
            if($this->param['type']==2){
                $data['account'] = $this->param['account'];
                $data['period']=$ticket['period'];
                $data['price']=$ticket['price'];
            }else{
                if($this->param['type']==3){
                    $data['month']=$this->param['month'];
                    $data['account']=$this->param['account'];
                    $data['card_type']=$this->param['card_type'];
                    $data['price']=$ticket['real_price'];
                }else{
                    $data['period']=$ticket['period'];
                    $data['price']=$ticket['price'];
                }
            }
            
           Db::name('application_order')->insert($data);
           $order_id = Db::name("application_order")->getLastInsID();
            Db::commit();
            echo json_encode(ajaxreturn(0,lang('提交成功'),$order_id));
        }catch (\Exception $e){
            Db::rollback();
            echo json_encode(ajaxreturn(1,lang('提交失败'.$e->getMessage())));
        }

    }


    public function order_list(){
      $userid = decoded_user_token(input("user_token"),'member_id');
        $limit=$this->param['list_rows']?$this->param['list_rows']:10;
        $page=$this->param['page']?$this->param['page']:1;
        $where=['user_id'=>$userid];
        if(!empty($this->param['type'])){
            switch ($this->param['type']){
                case 1:
                    //今天

                    $where['a.create_time']=['between',[getTodayStart(),getTodayEnd()]];
                    break;
                case 2:
                    //昨天
                    $where['a.create_time']=['between',[getTodayStart()-86400,getTodayEnd()-86400]];
                    break;
                case 3:
                    //  前天
                    $where['a.create_time']=['between',[getTodayStart()-86400*2,getTodayEnd()-86400*2]];

                    break;
                case 4:
                    //近7天
                    $where['a.create_time']=['between',[getTodayStart()-86400*7,TIME_NOW]];

                    break;
                case 5:

                    //近15天
                    $where['a.create_time']=['between',[getTodayStart()-86400*15,TIME_NOW]];

                    break;
                case 6:
//              //近30天
                    $where['a.create_time']=['between',[getTodayStart()-86400*30,TIME_NOW]];
                    break;
            }
        }


        if (!empty($this->param['start_time'])) {
            if (!empty($this->param['end_time'])) {
                $where['a.create_time']=['between',[strtotime($this->param['start_time'] . ' 00:00:00'),strtotime($this->param['end_time'] . ' 23:59:59')]];

            } else {
                $where['a.create_time']=['between',[strtotime($this->param['start_time'] . ' 00:00:00'),strtotime($this->param['start_time'] . ' 23:59:59')]];

            }
        }
        if(!empty($this->param['status'])  || $this->param['status']=='0' ){
            $where['a.status']=$this->param['status'];
        }

        $lists = Db::name('application_order')->alias('a')->field('a.*,b.type,b.logo,name')->join('__APPLICATION__ b', 'a.app_id = b.id')->where($where)->limit($limit)->page($page)->order('a.id desc')->select();
        $count=Db::name('application_order')->alias('a')->field('a.*,b.type,b.logo,name')->join('__APPLICATION__ b', 'a.app_id = b.id')->where($where)->count();

        foreach ($lists as $k=>$v){
            $lists[$k]['logo']=get_picture_url($v['logo'],false);
            $lists[$k]['create_time'] = date("Y-m-d H:i:s",$v['create_time']);
        }


        echo json_encode(ajaxreturn(0,lang('查询成功'),['total'=>$count,'per_page'=>$limit,'current_page'=>$page,'last_page'=>ceil($count/$limit),'data'=>$lists]));

    }

    public function order_detail(){
        $id = input('id');
        $detail = Db::name('application_order')->alias('a')->field('a.*,b.type,name')->join('__APPLICATION__ b', 'a.app_id = b.id')->where(['a.id'=>$id])->find();
        if(empty($detail)){
            echo json_encode(ajaxreturn(1,lang('订单不存在')));
        }else{

            echo json_encode(ajaxreturn(0,lang('查询成功'),$detail));
        }
    }

    public function application_ticket_class(){
        $id = input('id');
        $limit=$this->param['list_rows']?$this->param['list_rows']:10;
        $page=$this->param['page']?$this->param['page']:1;
        $lists = Db::name('application_ticket')->alias('a')->field('a.*,b.type,b.logo,b.name')->join('__APPLICATION__ b', 'a.app_id = b.id')->where(['a.app_id'=>$id,'a.status'=>1])->limit($limit)->page($page)->order('a.id desc')->select();
        $count=Db::name('application_ticket')->alias('a')->join('__APPLICATION__ b', 'a.app_id = b.id')->where(['a.app_id'=>$id,'a.status'=>1])->count();

            foreach ($lists as $k=>$v){
                $lists[$k]['logo']=get_picture_url($v['logo']);
            }
            echo json_encode(ajaxreturn(0,lang('查询成功'),['total'=>$count,'per_page'=>$limit,'current_page'=>$page,'last_page'=>ceil($count/$limit),'data'=>$lists]));

    }

    //用户券列表
    public function application_user_ticket(){
        $userid = decoded_user_token(input("user_token"),'member_id');
        $app_id = input('app_id');
        if(empty($this->param['list_rows'])){
            $limit = 10;
        }else{
            $limit = $this->param['list_rows'];
        }

        if(empty($this->param['page'])){
            $page = 1;
        }else{
            $page = $this->param['page'];
        }
        if(empty($this->param['app_id'])){
            $list = Db::name("application_user_ticket")->alias('a')->field("a.*,b.type,b.logo,b.name")->join('__APPLICATION__ b','a.app_id = b.id')->where(['a.user_id'=>$userid])->limit($limit)->page($page)->order('a.id desc')->select();
            
            $count = Db::name('application_user_ticket')->alias('a')->field('a.*,b.type,b.logo,b.name')->join('__APPLICATION__ b', 'a.app_id = b.id')->where(['a.user_id'=>$userid])->count();
        }else{
            $list = Db::name('application_user_ticket')->alias('a')->field('a.*,b.type,b.logo,b.name')->join('__APPLICATION__ b', 'a.app_id = b.id')->where(['a.user_id'=>$userid,'a.app_id'=>$app_id])->limit($limit)->page($page)->order('a.id desc')->select();
        
            $count = Db::name('application_user_ticket')->alias('a')->field('a.*,b.type,b.logo,b.name')->join('__APPLICATION__ b', 'a.app_id = b.id')->where(['a.user_id'=>$userid,'a.app_id'=>$app_id])->count();
        }
        

        foreach ($list as $k=>$v){
            $list[$k]['logo']=get_picture_url($v['logo'],false);
            $list[$k]['expire_time']=date("Y-m-d H:i:s",$v['expire_time']);
        }
        echo json_encode(ajaxreturn(0,lang('查询成功'),['total'=>$count,'per_page'=>$limit,'current_page'=>$page,'last_page'=>ceil($count/$limit),'data'=>$list]));

    }

    public function application_ticket_detail(){
        $id = input('id');
        $ticket = Db::name("application_ticket")->alias('a')->field('a.*,b.logo')->join('__APPLICATION__ b', 'a.app_id = b.id')->where(['a.id'=>$id,'a.status'=>1])->find();
        if(empty($ticket)){
            echo json_encode(ajaxreturn(1,lang('数据不存在')));
        }else{
            $ticket['create_time']=date('Y-m-d H:i:s',$ticket['create_time']);
            $ticket['update_time']=date('Y-m-d H:i:s',$ticket['update_time']);
            $ticket['describe']  = html_change(Db::name("application")->where(['id'=>$ticket['app_id']])->find()['describer']);
            $ticket['logo']=get_picture_url($ticket['logo']);
            echo json_encode(ajaxreturn(0,lang('查询成功'),$ticket));
        }
    }

    public function order_commit(){
        $id = input('id');
        $order = Db::name("application_order")->where(['id'=>$id])->find();
        if(empty($order)){
            echo json_encode(ajaxreturn(1,lang('订单不存在')));exit;
        }
        $userid = decoded_user_token(input("user_token"),'member_id');
        $member=Member::get($userid);
        //判断用户余额
        if($member['app_balance']<$order['price']){
            echo json_encode(ajaxreturn(1,lang('应用余额不足')));exit;
        }
        Db::startTrans();
        try{
            $member->app_balance-=$order['price'];
            $member->save();
            $log = array(
                "user_id"=>$userid,
                "type"=>5,
                'is_add'=>2,
                'create_time'=>time(),
                'update_time'=>time(),
                'status'=>1,
                'serial_number'=>$order['sn'],
                'number'=> $order['price']
            );
            Db::name('app_account_log')->insert($log);
            BonusLog::create([
                "user_id"=>$userid,
                "type"=>4,
                'number'=> $order['price']
            ]);
            Db::name('application_order')->where(['id'=>$id])->update(['status'=>1]);
            Db::commit();
            echo json_encode(ajaxreturn(0,lang('提交成功')));
        }catch (\Exception $e){
            Db::rollback();
            echo json_encode(ajaxreturn(1,lang('提交失败'.$e->getMessage())));
        }
    }

    public function order_cancel(){
        $id = input('id');
        Db::startTrans();
        try{
            Db::name('application_order')->where(['id'=>$id])->update(['status'=>-1]);
            Db::commit();
            echo json_encode(ajaxreturn(0,lang('取消成功')));
        }catch (\Exception $e){
            Db::rollback();
            echo json_encode(ajaxreturn(1,lang('取消失败'.$e->getMessage())));
        }
    }



    /***
     * 会员卡套餐列表
     */
    public function  member_card_list(){
        $id = input('id');
        $level=Db::name('application_membercard')->where(['app_id'=>$id,'status'=>1])->group('level')->select();
        $arrs=[];
        foreach ($level as $k=>$v){
            $list=Db::name('application_membercard')->where(['app_id'=>$id,'level'=>$v['level'],'status'=>1])->order('id desc')->select();
            $arr['level']=$v['level'];
            $arr['list']=$list;
            $arrs[]=$arr;
        }

        echo json_encode(ajaxreturn(0,lang('查询成功'),$arrs));
    }
}
